/* global alert */
import api from 'api/login'
import base from 'api/student/base'
import Cookies from 'js-cookie'
export default {
  state: {
    user: {
      id: '',
      token: '',
      name: '',
      roles: 0,
      info: {}
    }
  },
  mutations: {
    postUser (context, payload) {
      context.user = payload
    },
    postInfo (context, payload) {
      context.user.info = payload
    }
  },
  actions: {
    login ({ commit }, payload) {
      return new Promise((resolve, reject) => {
        api.login(payload).then(({ data }) => {
          const _data = data.data
          if (data.success) {
            commit('postUser', {
              id: _data.userId,
              token: _data.token,
              roles: _data.roles[0].name,
              name: _data.name,
              info: {}
            })
            Cookies.set('token', _data.token)
            Cookies.set('id', '' + _data.userId)
            Cookies.set('roles', _data.roles[0].name)
            Cookies.set('name', _data.name)
            resolve(_data)
          } else {
            const error = true
            reject(error)
          }
        })
      })
    },
    getUserInfo ({commit, state}) {
      return base.info('' + state.user.id).then(({data}) => {
        commit('postInfo', data.data[0])
      })
    },
    logout ({commit, state}) {
      return api.logout(state.user.id).then(() => {
        commit('postUser', {
          id: '',
          token: '',
          name: '',
          roles: 0,
          info: {}
        })
        Cookies.remove('token')
        Cookies.remove('id')
        Cookies.remove('roles')
        Cookies.remove('name')
      })
    }
  }
}
